const inspirecloud = require('@byteinspire/api')


// 创建token
const setToken = async function(userName) {
  const time = Date.now()
  const tk = userName + time
  const Tokens = inspirecloud.db.table('tokens');
  const UserLoginTime = inspirecloud.db.table('user-login-time')
  const loginTimeInfo = UserLoginTime.create({username: userName});
  UserLoginTime.save(loginTimeInfo)
  let tokenItem = await Tokens.where({username: userName}).findOne()  // String
  if (!tokenItem) {
    tokenItem = Tokens.create({username: userName, token: tk});
  }
  tokenItem.token = tk
  await Tokens.save(tokenItem);
  return tk
}


// 验证token
const trueToken = async function(userToken) {
  let limitTime = 172800000                                             // 过期时间
  const Tokens = inspirecloud.db.table('tokens');
  const tokenInfo = await Tokens.where({token: userToken}).findOne()  
  if (tokenInfo && JSON.stringify(tokenInfo) != "{}") {
    const nowTime = Number(Date.now())
    const tokenTime = Number(new Date(tokenInfo.updatedAt).getTime())
    if (nowTime - tokenTime < limitTime) {
      return tokenInfo
    }
  }
  return false
}


// 通过username查找token
const findTokenByUserName = async function(userName) {
  const Tokens = inspirecloud.db.table('tokens');
  const tokenInfo = await Tokens.where({username: userName}).findOne();  
  return tokenInfo
}


// 创建code
const createCodeByUserName = async function() {
  const passCode = parseInt(Math.random() * 10000)
  return passCode
}



module.exports = {
  setToken,
  trueToken,
  findTokenByUserName,
  createCodeByUserName
}